package com.svmc.app.task.activity;

import java.util.ArrayList;
import java.util.Calendar;

import luyenlv.pro.screen.base.BaseActivity;
import android.content.Intent;
import android.database.Cursor;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.svmc.app.task.adapter.DbAdapter;
import com.svmc.app.task.alarm.MyAlarmManager;
import com.svmc.app.task.model.CalenderModel;
import com.svmc.app.task.model.TaskModel;
import com.svmc.app.task.tabmanager.TabGroupActivity;
import com.svmc.app.task.utils.CommonDefine;
import com.svmc.app.task.utils.DateUtils;
import com.svmc.app.task.utils.UtilString;
import com.svmc.app.task.view.DateDialog;

public class EditTask extends BaseActivity implements OnClickListener,
		CommonDefine {
	ArrayList<TaskModel> listtask;
	private static String txt_timeReminder = "";
	DateUtils dateUtils = new DateUtils();
	EditText task, note;
	CheckBox cb_isreminder;
	TextView timefinish, timereminder, titleRing, namefilering;
	Calendar c = Calendar.getInstance();
	Calendar c1 = Calendar.getInstance();
	// Spinner choseRingtone;
	RelativeLayout rl_reminder;
	ImageView choseRingtone;
	String pathRing ="Default Ring"+":"+R.raw.sound_default;
	UtilString utils;
	int id_cancel_alarm;
	int id;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(getLayout(R.array.addnew_layout));

		findViewById(R.id.addnew_img_back).setOnClickListener(this);
		findViewById(R.id.addnew_img_done).setOnClickListener(this);
		findViewById(R.id.addnew_spinner_ringtone).setOnClickListener(this);

		titleRing = (TextView) findViewById(R.id.addnew_txt_label_ringtone);
		namefilering = (TextView) findViewById(R.id.addnew_txt_titleRing);
		namefilering.setText(getString(R.string.default_ringtone_label));
		task = (EditText) findViewById(R.id.addnew_edt_newtask);
		note = (EditText) findViewById(R.id.addnew_edt_note);
		cb_isreminder = (CheckBox) findViewById(R.id.addnew_cb_isReminder);
		cb_isreminder.setOnClickListener(this);

		timefinish = (TextView) findViewById(R.id.addnew_txt_timefinish);
		timereminder = (TextView) findViewById(R.id.addnew_txt_timereminder);
		timefinish.setOnClickListener(this);
		timereminder.setOnClickListener(this);
		utils = new UtilString();
		Log.i("test Strinh date", c.getTime().toString());
		// choseRingtone = (Spinner) findViewById(R.id.addnew_spinner_ringtone);

		rl_reminder = (RelativeLayout) findViewById(R.id.addnew_rl_reminder);
		// cb_isreminder.setChecked(false);
		// hideViewSetReminder();
		Log.i("Status activity", "onCreate Editactivity");

		/*
		 * timefinish.setText(dateUtils.getCurrentTime(c)); txt_timeReminder =
		 * dateUtils.getCurrentTime(c);
		 * timereminder.setText(dateUtils.getCurrentTime(c));
		 */
		Bundle data = getIntent().getExtras();
        id = data.getInt("id_task");
		filldata(id);

	}

	@Override
	protected void onResume() {
		super.onResume();
		// hideAndShowReminder();

		// int id = bundle.getInt("id_task");
		// DbAdapter db = new DbAdapter(this);
		// TaskModel taskupdate = db.getTaskById(id);
		// showToast("ID" + id, 0);
		// timefinish.setText(dateUtils.textDateForshow(taskupdate.getTimefinish()));
		// task.setText(taskupdate.getTask());
		// note.setText(taskupdate.getNote());
		Log.i("Status activity", "onResume Editactivity");

	}
	@SuppressWarnings("unused")
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		//showToast("onsave addnew", 0);
				if(TabGroupActivity.isdestroy==true && TabGroupActivity.isstop==true){
					//showToast("onsave addnew =true", 0);
					TabGroupActivity.stateActivity=EDIT_ACTIVITY;
					TabGroupActivity.id_data=id;
					TabGroupActivity.isdestroy=false;
					TabGroupActivity.isstop=false;
				}else if (TabGroupActivity.isdestroy=false&&TabGroupActivity.isstop==true) {
					TabGroupActivity.isdestroy=false;
					TabGroupActivity.isstop=false;
				}
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.addnew_img_back:
			// showToast(pathRing, 0);
			finish();
			//finishFromChild(this);
			break;
		case R.id.addnew_img_done:
			MyAlarmManager alarm = new MyAlarmManager(this);
			if (cb_isreminder.isChecked()) {
				 int id_alarm = (int) System.currentTimeMillis();

				// long row = addnewtask(task.getText().toString(), c, 1,
				// c1,note.getText().toString(),id_alarm,pathRing);
				int row = updateTask(id,task.getText().toString(), c, REMINDER, c1, note.getText().toString(), id_alarm, pathRing);
				if(row>0){
					 alarm.cancelAlarm(id_cancel_alarm);
					 showToast("Update thanh cong", Toast.LENGTH_LONG);
					 Log.i("Time reminder : ", c1.getTime().toString());
					 alarm.SingleAlarmWithData(c1, id_alarm, id);
					 InputMethodManager imm = (InputMethodManager)getSystemService(this.INPUT_METHOD_SERVICE);
				        imm.hideSoftInputFromWindow(task.getWindowToken(), 0);
				        imm.hideSoftInputFromWindow(note.getWindowToken(), 0);
				        finish();
				        //finishFromChild(this);
				}else {
					 showToast("Can't update task", Toast.LENGTH_LONG);
				}
				
				
			} else {
				 int row = updateTask(id,task.getText().toString(), c, NOT_REMINDER,
				 c1,note.getText().toString(),-1,pathRing);
				 if(row>0) {
					 alarm.cancelAlarm(id_cancel_alarm);
					 showToast("Update thanh cong", Toast.LENGTH_LONG);
					 InputMethodManager imm = (InputMethodManager)getSystemService(this.INPUT_METHOD_SERVICE);
				        imm.hideSoftInputFromWindow(task.getWindowToken(), 0);
				        imm.hideSoftInputFromWindow(note.getWindowToken(), 0);
				        finish();
				        //finishFromChild(this);
				 }else {
					showToast("Can't update task", 0);
				}
			}
			
			break;
		case R.id.addnew_txt_timefinish:
			TabGroupActivity.isdestroy=false;
			Intent timefinishIntent = new Intent(this, DateDialog.class);
			timefinishIntent.putExtra("send_year", c.get(Calendar.YEAR));
			timefinishIntent.putExtra("send_month", c.get(Calendar.MONTH));
			timefinishIntent.putExtra("send_day", c.get(Calendar.DAY_OF_MONTH));
			timefinishIntent.putExtra("send_hour", c.get(Calendar.HOUR_OF_DAY));
			timefinishIntent.putExtra("send_minute", c.get(Calendar.MINUTE));
			timefinishIntent.putExtra(EDIT_OR_NEW,ACTIVITY_EDIT);
			//startActivityForResult(timefinishIntent, REQUEST_CODE_TIME_FINISH);
			//startActivityForResult(timefinishIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP),REQUEST_CODE_TIME_FINISH);
			this.getParent().startActivityForResult(timefinishIntent, REQUEST_CODE_TIME_FINISH);
			break;
		case R.id.addnew_txt_timereminder:
			TabGroupActivity.isdestroy=false;
			Intent timeReminderIntent = new Intent(this, DateDialog.class);
			timeReminderIntent.putExtra("send_year", c1.get(Calendar.YEAR));
			timeReminderIntent.putExtra("send_month", c1.get(Calendar.MONTH));
			timeReminderIntent.putExtra("send_day",c1.get(Calendar.DAY_OF_MONTH));
			timeReminderIntent.putExtra("send_hour",c1.get(Calendar.HOUR_OF_DAY));
			timeReminderIntent.putExtra("send_minute", c1.get(Calendar.MINUTE));
			timeReminderIntent.putExtra(EDIT_OR_NEW, ACTIVITY_EDIT);
			this.getParent().startActivityForResult(timeReminderIntent,REQUEST_CODE_TIME_REMINDER);
			break;
		case R.id.addnew_cb_isReminder:

			if (cb_isreminder.isChecked() == false) {
				hideViewSetReminder();
			} else {
				showViewSetReminder();
				timereminder.setText(txt_timeReminder);
				c1 = c;

				// getPathRingtone();
			}

			break;
		case R.id.addnew_spinner_ringtone:
			TabGroupActivity.isdestroy=false;
			Intent ringIntent = new Intent(this, SelectRingtone.class);
			ringIntent.putExtra(EDIT_OR_NEW, ACTIVITY_EDIT);
			this.getParent().startActivityForResult(ringIntent, REQUEST_CODE_SELECT_RINGTONE);
			break;
		default:
			break;
		}

	}
	


	public void handeonActivityResult(int requestCode, int resultCode, Intent data) {
		int year, month, day, hour, minute;
		switch (requestCode) {

		case REQUEST_CODE_TIME_FINISH:
			if (resultCode == RESULT_OK) {
				try {
					Bundle bundle = data.getExtras();
					year = bundle.getInt("year");
					month = bundle.getInt("month");
					day = bundle.getInt("day");
					hour = bundle.getInt("hour");
					minute = bundle.getInt("minute");
					c = dateUtils.setTime(year, month, day, hour, minute);
					timefinish.setText(dateUtils.formatDateToShow(c));
					txt_timeReminder = dateUtils.formatDateToShow(c);
				} catch (NullPointerException e) {

				}

			}
			break;
		case REQUEST_CODE_TIME_REMINDER:
			if (resultCode == RESULT_OK) {
				try {
					Bundle bundle = data.getExtras();
					year = bundle.getInt("year");
					month = bundle.getInt("month");
					day = bundle.getInt("day");
					hour = bundle.getInt("hour");
					minute = bundle.getInt("minute");
					c1 = dateUtils.setTime(year, month, day, hour, minute);
					timereminder.setText(dateUtils.formatDateToShow(c1));
				} catch (NullPointerException e) {

				}

			}
			break;
		case REQUEST_CODE_SELECT_RINGTONE:
			if (resultCode == RESULT_OK) {
				try {
					Bundle bundle = data.getExtras();
					String title = bundle.getString("titleRing");
					//pathRing = bundle.getString("pathRing");
					namefilering.setText(title);
					String pathringtone = bundle.getString("pathRing");
					UtilString utils = new UtilString();
					pathRing = utils.formatStringPutData(title, pathringtone);
				} catch (NullPointerException e) {
					namefilering.setText("nullpointer");
				}

			}
			break;
		default:
			break;
		}
	}

	/**
	 * add new task
	 * 
	 * @param tasknote
	 * @param duedate
	 * @param isreminder
	 * @param timereminder
	 */
	public long addnewtask(String tasknote, Calendar duedate, int isreminder,
			Calendar timereminder, String note, int idAlarm, String pathRing) {
		TaskModel task = new TaskModel();
		long row = 0;
		DbAdapter db = new DbAdapter(this);
		task.setTask(tasknote);
		task.setIsreminder(isreminder);
		task.setTimefinish(duedate.getTime().toString());

		task.setNote(note);
		if (isreminder == 1) {

			task.setTimereminder(timereminder.getTime().toString());
			task.setId_alarm(idAlarm);
			task.setPathRingtone(pathRing);
			row = db.addTask(task);
		} else {
			row = db.addTask(task);
		}
		return row;

	}
	/**
	 * update taskModel
	 * 
	 * @param tasknote
	 * @param duedate
	 * @param isreminder
	 * @param timereminder
	 */
	public int updateTask(int id,String tasknote, Calendar duedate, int isreminder,
			Calendar timereminder, String note, int idAlarm, String pathRing) {
		int row = 0;
		TaskModel task = new TaskModel();
		DbAdapter db = new DbAdapter(this);
		task.setId(id);
		task.setTask(tasknote);
		task.setIsreminder(isreminder);
		task.setTimefinish(dateUtils.formatDate(duedate));
		task.setNote(note);
		if (isreminder == 1) {
			task.setTimereminder(dateUtils.formatDate(timereminder));
			task.setId_alarm(idAlarm);
			task.setPathRingtone(pathRing);
			row = db.updateStatusTask(task);
		}else {
			row = db.updateStatusTask(task);
		}
		
		return row;
	}

	public void showViewSetReminder() {
		rl_reminder.setVisibility(View.VISIBLE);

	}

	public void hideViewSetReminder() {
		rl_reminder.setVisibility(View.GONE);
	}

	Ringtone ring = null;

	public void getPathRingtone() {
		/*
		 * List<String> list = new ArrayList<String>(); list.add("list 1");
		 * list.add("list 2"); list.add("list 3"); ArrayAdapter<String>
		 * dataAdapter = new ArrayAdapter<String>(this,
		 * android.R.layout.simple_spinner_item, list);
		 * dataAdapter.setDropDownViewResource
		 * (android.R.layout.simple_spinner_dropdown_item);
		 * 
		 * choseRingtone.setAdapter(dataAdapter);
		 */

		RingtoneManager mRingtone = new RingtoneManager(this);

		mRingtone.setType(RingtoneManager.TYPE_RINGTONE);
		mRingtone.setIncludeDrm(true);
		Cursor mCursor = mRingtone.getCursor();
		startManagingCursor(mCursor);
		// String test =
		// mCursor.getString(mCursor.getColumnIndexOrThrow(RingtoneManager.EXTRA_RINGTONE_TITLE));
		String[] from = { mCursor
				.getColumnName(RingtoneManager.TITLE_COLUMN_INDEX) };
		int[] to = { android.R.id.text1 };
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
				android.R.layout.simple_spinner_item, mCursor, from, to);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		/*
		 * choseRingtone.setAdapter(adapter);
		 * choseRingtone.setOnItemSelectedListener(new OnItemSelectedListener()
		 * {
		 * 
		 * @Override public void onItemSelected(AdapterView<?> parentView, View
		 * view, int position, long id) { if(ring ==null){ RingtoneManager r =
		 * new RingtoneManager(getApplicationContext()); ring =
		 * r.getRingtone(position); //ring.play(); }else { ring.stop();
		 * RingtoneManager r = new RingtoneManager(getApplicationContext());
		 * ring = r.getRingtone(position); ring.play(); } showToast("select : "
		 * +position, 0); }
		 * 
		 * @Override public void onNothingSelected(AdapterView<?> arg0) {
		 * 
		 * 
		 * }
		 * 
		 * });
		 */
	}

	public void hideAndShowReminder() {
		if (cb_isreminder.isChecked() == false) {
			hideViewSetReminder();
		} else {
			showViewSetReminder();
			timereminder.setText(txt_timeReminder);
			c1 = c;
			// isFirstSelectRing = 1;
			// getPathRingtone();
		}
	}

	public void showToast(String text, int type) {
		Toast.makeText(this, text, type).show();
	}

	/**
	 * get all task from database
	 * 
	 * @return
	 */
	public ArrayList<TaskModel> getAllTask() {
		DbAdapter db = new DbAdapter(this);
		return db.getAllTask();
	}

	/**
	 * fill all data to form
	 * 
	 * @param data
	 */
	public void filldata(int id) {
		DbAdapter db = new DbAdapter(this);
		TaskModel taskupdate = db.getTaskById(id);
		task.setText(taskupdate.getTask());
		txt_timeReminder = taskupdate.getTimefinish();
		/*
		 * Set calender for time finish
		 */
		CalenderModel calfinish = dateUtils.ConvertimeDate(taskupdate
				.getTimefinish());
		c.set(Calendar.YEAR, calfinish.getYear());
		c.set(Calendar.MONTH, calfinish.getMonth() - 1);
		c.set(Calendar.DAY_OF_MONTH, calfinish.getDay());
		c.set(Calendar.HOUR_OF_DAY, calfinish.getHour());
		c.set(Calendar.MINUTE, calfinish.getMinute());
		/*
		 * set Calender for timeReminder
		 */
		if (taskupdate.getTimereminder() != null) {
			CalenderModel calreminder = dateUtils.ConvertimeDate(taskupdate
					.getTimereminder());
			c1.set(Calendar.YEAR, calreminder.getYear());
			c1.set(Calendar.MONTH, calreminder.getMonth() - 1);
			c1.set(Calendar.DAY_OF_MONTH, calreminder.getDay());
			c1.set(Calendar.HOUR_OF_DAY, calreminder.getHour());
			c1.set(Calendar.MINUTE, calreminder.getMinute());
		}
			if(taskupdate.getPathRingtone() !=null){
				namefilering.setText(utils.getTitleRing(taskupdate.getPathRingtone()));
				pathRing = taskupdate.getPathRingtone();
			}
		id_cancel_alarm = taskupdate.getId_alarm();
		Log.i("ID alarm : ", ""+id_cancel_alarm);
		/*
		 * ======================================
		 */
		if (taskupdate.getNote() != null) {
			note.setText(taskupdate.getNote());
		}
		timefinish.setText(dateUtils.formatDateToShow(c));
		if (taskupdate.getIsreminder() == 1) {
			cb_isreminder.setChecked(true);
			showViewSetReminder();
			timereminder.setText(dateUtils.formatDateToShow(c1));

		} else {
			cb_isreminder.setChecked(false);
			hideViewSetReminder();
		}

		
	}
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		TabGroupActivity.isstop=true;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		TabGroupActivity.isdestroy=true;
		task = null;
		note = null;
		dateUtils = null;
		cb_isreminder = null;
		timefinish = null;
		timereminder = null;
		titleRing = null;
		namefilering = null;
		choseRingtone = null;
		System.gc();
		Log.i("Status activity", "onDestroy Editactivity");
	}

	@Override
	public void clearMemory() {

	}

}
